package edu.dayu.callback;

import edu.dayu.entity.pojo.MsgRecord;
import edu.dayu.mapper.MsgRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class MsgCallback implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MsgRecordMapper msgRecordMapper;

    @PostConstruct
    public void init(){
        //注入
        rabbitTemplate.setConfirmCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        String id = correlationData.getId();
        MsgRecord record = new MsgRecord();
        record.setId(Long.parseLong(id));
        if (StringUtils.hasLength(s)){
            log.error("消息:{}发送失败,原因:{}",id,s);
            record.setFailResult(s);
        }else {
            record.setStatus(2);
        }
        msgRecordMapper.updateById(record);
    }
}
